package com.tc.itfarm.admin.action.system;

import com.tc.itfarm.api.exception.BusinessException;
import com.tc.itfarm.api.model.Page;
import com.tc.itfarm.model.Menu;
import com.tc.itfarm.service.ArticleService;
import com.tc.itfarm.service.MenuArticleService;
import com.tc.itfarm.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by wangdongdong on 2016/9/8.
 */
@Controller
@RequestMapping("/menu")
public class MenuAction {

    private static final Logger logger = LoggerFactory.getLogger(MenuAction.class);

    @Resource
    private MenuService menuService;
    @Resource
    private ArticleService articleService;
    @Resource
    private MenuArticleService menuArticleService;

    @RequestMapping("/list")
    public String list(Model model) {
        List<Menu> menus = menuService.selectAll();
        model.addAttribute("menus", menus);
        return "admin/menu/list";
    }

    @RequestMapping("/editUI")
    public String editUI(Model model, Integer id) {
        Menu menu = menuService.select(id);
        List<Menu> menus = menuService.selectAll();
        model.addAttribute("menu", menu);
        model.addAttribute("maxOrder", menuService.selectMaxOrder(null));
        model.addAttribute("articles", articleService.selectAll());
        List<Integer> ids = menuArticleService.selectArticleByMenuId(id, new Page(0, 100));
        model.addAttribute("ids", ids);
        model.addAttribute("menus", menus);
        return "admin/menu/add_menu";
    }

    @RequestMapping("/addUI")
    public String addUI(Model model) {
        List<Menu> menus = menuService.selectAll();
        model.addAttribute("menus", menus);
        model.addAttribute("maxOrder", menuService.selectMaxOrder(null));
        model.addAttribute("articles", articleService.selectAll());
        return "admin/menu/add_menu";
    }

    @RequestMapping("/save")
    public String save(Model model, Menu menu, Integer ids[]) {
        try {
            menuService.save(menu, ids);
        } catch (BusinessException e) {
            logger.error(e.getMessage(), e);
        }
        return "redirect:list.do";
    }

    @RequestMapping("/delete")
    public String delete(Integer id) {
        menuService.delete(id);
        return "redirect:list.do";
    }

}
